<?php
define('ipos',true);
include_once("../include/config.php");
require 'src/facebook.php';
$facebook = new Facebook(array(
  'appId'  => '237063196360012',
  'secret' => '24b0272ad35db574692155dfcab7fcb6',
));
$user = $facebook->getUser();
if ($user) {
  try {
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
	$checkfacebookid		= 	$db->database("facebookid","user","facebookid = '".$user_profile["id"]."'");
	if (!$checkfacebookid) {
		$username		=	$user_profile["username"];
		$email			=	$user_profile["email"];
		$fullname		=	$user_profile["last_name"]." ".$user_profile["first_name"];
		$birthday		=	$user_profile["birthday"];
		$avatar			=	'https://graph.facebook.com/'.$user_profile['id'].'/picture?type=large';
		$facebookid			=	$user_profile["id"];
		$sex			=	$user_profile['gender'];
		if($sex=='male'){
			$sex='0';
		}else{
			$sex='1';
		}
		$checkemail		= 	$db->database("userid","user"," email = '$email'");
		$checkuser		= 	$db->database("userid","user"," username = '$username'");
		// kiểm tra
		if($checkuser) {
			$error	.=	"+ Tài khoản đã được sử dụng!<br>";
		}
		if($checkemail) {
			$error	.=	"+ Email đã được sử dụng!<br>";
		}
		// check error
		if($error) {
			$error	=	"<span>Lỗi:</span><br>".$error;
		}
		else {
			$usercode	=	rand(1000,9999);
			$regdate	=	NOW;
			$db->dbinstall("user","username,email,usercode,sex,fullname,regdate,birthday,avatar,facebookid","'$username','$email','$usercode','$sex','$fullname','$regdate','$birthday','$avatar','$facebookid'");
			$id = mysql_insert_id();
			$_SESSION["ipos_userid"] 	= $id;
			$_SESSION["ipos_usergroup"] = '0';
			$_SESSION["ipos_username"] 	= $username;
		}
	} else {
			$arr 		= $db->database("userid, usergroup, username, usercode ","user","facebookid = '".$user_profile["id"]."'");
			$_SESSION["ipos_userid"] 	= $arr[0][0];
			$_SESSION["ipos_usergroup"] = $arr[0][1];
			$_SESSION["ipos_username"] 	= $arr[0][2];
	}
	header("Location: /");
} else {
  $loginUrl = $facebook->getLoginUrl();
  header("Location: ".$loginUrl);
}
?>